/**
 * User: zhangqiang Date: 15-8-11 Time: 上午11:04 查询面板
 */

define(
    "require dojo/_base/declare dojo/_base/lang dojo/_base/array dojo/_base/fx dojo/fx/easing ../../util/ajaxUtil dojo/dom dojo/dom-attr dojo/dom-class dojo/dom-style dojo/on dojo/query dijit/layout/ContentPane dojo/topic ../BaseWidget dojo/text!./templates/Template.html"
        .split(" "), function(require, declare, lang, array, baseFx, easing,
        ajaxUtil, dom, domAttr, domClass, domStyle, on, query, ContentPane,
        topic, BaseWidget, template) {
	    return declare([ BaseWidget ],
	        {
	          templateString : template,
	          selCityCode : null,
	          constructor : function(args) {
	          },
	          postCreate : function() {
		          this.addEvents();
		          this._initCityList();// 初始化城市列表
		          this.selCityCode = '440100';
		          this._initSearchCheckForm();// 初始化poi搜索类型选择窗体
	          },
	          startup : function() {
		          this.inherited(arguments);
	          },
	          destroy : function() {
		          var widgets = this.widgets;
		          for ( var name in widgets) {
			          if (widgets[name]) {
				          widgets[name].destroy();
			          }
		          }
		          this.inherited(arguments);
	          },
	          /**
						 * 添加事件
						 */
	          addEvents : function() {
	        	   
	        	  if(ioc.map.userInfoData.USERTYPE=='todo'){ //TODO 待定权限控制
	        		  
		              var poi =false;
		              var advanceSearch=false;
		        	  if(ioc.map.userRoleModule){
		        		  var  array = $.parseJSON(ioc.map.userRoleModule);
		        		  for(var i=0 ; i<array.length;i++){
		        			  if(array[i].MODEL_NAME =='POI搜索'){poi = true }
		        			  else if(array[i].MODEL_NAME =='高级查询'){advanceSearch = true }
		        		  }
		        	  }
		        	  
		        	  // 高级查询显示控制
		        	  if(advanceSearch){
				          on(this.advancesearch, "click", lang.hitch(this,
					              this._advancesearch( )));
		        	  }else{
		        		  this.advancesearch.style.display='none'
		        	  }
		        	  
		        	  //高级查询 + poi搜索显示控制
		        	  if(!poi && !advanceSearch){
		        		  this.poiHeartSearchDiv.style.display='none'
		        	  }
		        	  
	        	  }
			         
			          on(this.advancesearch, "click", lang.hitch(this,
				              this._advancesearch));// 高级查询
			          on(this.poiSearchbtn, "click", lang.hitch(this, function(evt) {
				          if(evt.target.className=='searchbtn'){
					          var searchWord = $("#address").val();
					          if (searchWord.trim() != "") {
						          this._poiSearch(searchWord);
					          }
				          }
			          }));
			          
			          on(document, "keyup", lang.hitch(this, function() {// 页面poi搜索
				          if (event.keyCode == 13) {
					          var searchWord = $("#address").val();
					          if (searchWord.trim() != "") {
						          this._poiSearch(searchWord);
					          }
				          }
			          }));
		           
		          
	          },
	          /**
						 * 页面内敲回车调用poi搜索服务
						 */
	          _poiSearch : function(keyword) {
		          require([ "gistech/widgets/PoiSearchWidget/PoiSearchWidget" ],
		              lang.hitch(this, function(PoiSearchWidget) {
		              	var searchtype=$('input[name="searchTypeRadio"]:checked').val();
		              	//if (!this.poiSearchWidget){
			              	this.poiSearchWidget = new PoiSearchWidget({
				                map : Global.widgets.mapWidget.map,
				                keyWord : keyword,
				                citycode : this.selCityCode,
				                searchtype:searchtype
				              });
			              	this.poiSearchWidget.startup();
		              	/*}
		              	  else{
		              		this.poiSearchWidget.keyWord=keyWord;
		              		this.poiSearchWidget.citycode=this.selCityCode;
		              		this.poiSearchWidget.searchtype=searchtype;
		              	}*/
		              }));
	          },
	          /**
						 * 在点击高级查询的时候就 弹出土地资源树
						 */
	          _advancesearch : function( ) {
	        	  

		          /*
							 * require(["gistech/widgets/LandResTree/LandResTree",], function
							 * (LandResTree){ var landResTree = new
							 * LandResTree({pos:{l:Math.ceil(document.body.clientWidth)/2-419,t:110}},dojo.byId("LandResTreeDialog"));
							 * landResTree.setTitle("土地资源树图表"); landResTree.startup(); });
							 */
		          // 前端热力图高级查询widget的调用
		          require([ "gistech/widgets/FrontHeatDiagram/FrontHeatDiagram", ],
		              lang.hitch(this, function(FrontHeatDiagram) {
			        	  
			              Global.currentUseFun = "advQuery";
			              if (!this.frontHeatDiagram) {
				              this.frontHeatDiagram = new FrontHeatDiagram({
				                pos : {
				                  l : Math.ceil(document.body.clientWidth) / 2 - 419,
				                  t : 90
				                },
				                "map" : Global.widgets.mapWidget.map
				              });
				              this.frontHeatDiagram.setTitle("高级查询");
				              this.frontHeatDiagram.startup();
			              } else {
				              $(this.frontHeatDiagram.domNode).show();
			              }
		              }));
	          },
  			  /**
			  * 初始化poi搜索选择框
			  */
	          _initSearchCheckForm : function() {
		          for ( var attr in ioc.poiSearch) {
		          	searchFormObj=$('#search_type_checkform');
			          if (typeof (ioc.poiSearch[attr]) == 'object') {
			          	searchFormObj.append('<div><label><input name="searchTypeRadio" type="radio" value="'+attr+'"/>'+ioc.poiSearch[attr]["name"]+' </label></div>');
			            $('input[name="searchTypeRadio"]:first').attr('checked', 'checked');
			          }
		          }
	          },
	          /**
						 * 初始化城市列表
						 */
	          _initCityList : function() {
		          // debugger
		          /** 默认城市数据 */
	          	var defaultCitys;
		          defaultCitys = [ {
		            "code" : "110000",
		            "name" : "北京",
		            "ymin" : 4831759.398,
		            "ymax" : 4873341.141,
		            "xmin" : 12922237.73,
		            "xmax" : 12991948.3
		          }, {
		            "code" : "310000",
		            "name" : "上海",
		            "ymin" : 3644823.148,
		            "ymax" : 3686404.891,
		            "xmin" : 13485318.4,
		            "xmax" : 13555028.97
		          }, {
		            "code" : "440100",
		            "name" : "广州",
		            "ymin" : 2573393.513,
		            "ymax" : 2745244.529,
		            "xmin" : 12574483.48,
		            "xmax" : 12697096.33
		          }, {
		            "code" : "120000",
		            "name" : "天津",
		            "ymin" : 4721514.497,
		            "ymax" : 4763096.241,
		            "xmin" : 13010251.21,
		            "xmax" : 13079961.78
		          }, {
		            "code" : "500000",
		            "name" : "重庆",
		            "ymin" : 3425302.089,
		            "ymax" : 3466883.832,
		            "xmin" : 11819045.95,
		            "xmax" : 11888756.52
		          }, {
		            "code" : "440300",
		            "name" : "深圳",
		            "ymin" : 2564264.23,
		            "ymax" : 2615307.937,
		            "xmin" : 12662753.94,
		            "xmax" : 12760382.58
		          }, {
		            "code" : "420100",
		            "name" : "武汉",
		            "ymin" : 3499575.599,
		            "ymax" : 3679755.041,
		            "xmin" : 12657280.02,
		            "xmax" : 12810933.43
		          } ];
		          // 初始化头部的默认城市
		          this._initHead(defaultCitys);
		          // 初始化城市列表主体内容
		          this._initCitys();
		          // 绑定事件
		          this._bindEvts();
	          },
	          _initHead : function(defaultCitys) {
		          var headHTML = "";
		          for ( var i in defaultCitys) {
			          $this = this;
			          var linkText = "<a href='javascript:void(0);'  data='"
			              + JSON.stringify(defaultCitys[i]) + "'>"
			              + defaultCitys[i]["name"] + "</a>";
			          headHTML += linkText;
		          }
		          $("#assist", this.domNode).append(headHTML);
		          $(".city-con .city").text("广州");
	          },
	          _initCitys : function() {
		          require([ "gistech/util/districts", ], lang.hitch(this, function(
		              districts) {
			          var groupInfo = [ "A", "F", "G", "H", "J", "L", "N", "Q", "S",
			              "X", "Y", "Z", "OTHER" ];
			          var curGroup, cityGroupTableHtml = "";
			          // 遍历分组,构造出所有分组的城市数据
			          for ( var i = 0; i < groupInfo.length; i++) {
				          curGroup = groupInfo[i];
				          var curPro, proCount = 0;// proCount：当前分组中省的数量
				          var title, tr = "";
				          // 构造出每一分组的城市数据,比如构造出分组为A的城市数据
				          for ( var j = 0; j < districts.length; j++) {
					          curPro = districts[j];
					          // 找到 districts.js数据中的省
					          if (curPro.group === curGroup) {
						          // 组内第一个省
						          if (proCount === 0) {
							          title = curPro.group;// 比如A
						          } else {
							          title = "";// 这个是针对比如curPro.group为G的有
																		// 贵州、广西、广东、甘肃四个省,只针对第一个贵州省设置title="A"
						          }
						          var letter_pro = "<td>" + title + "</td>";
						          // 省
						          var th_pro = "<th class='proName'><span>" + curPro.name
						              + "</span></th>";
						          // 遍历市
						          var td_citys = "<td class='citys'>";
						          for ( var k = 0; k < curPro.citys.length; k++) {
							          // 注意这里传递对象的时候 需要先使用JSON.stringify将json对象转换为字符串
							          td_citys += "<a href='Javascript:;' data='"
							              + JSON.stringify(curPro.citys[k]) + "'>"
							              + curPro.citys[k].name + "</a>";
						          }
						          td_citys += "</td>";
						          // 一行数据
						          tr += "<tr>" + letter_pro + th_pro + td_citys + "</tr>";
						          proCount++;
					          }
				          }
				          cityGroupTableHtml += "<table class='cityGroupDiv' name='"
				              + curGroup + "'>" + tr + "</table>";
			          }
			          // 将构造出来的各个分组的数据追加到 id="#content"元素上
			          $("#content", this.domNode).append(cityGroupTableHtml);
		          }));
	          },
	          _bindEvts : function() {
		          $(".city-con .city", this.domNode).click(
		              function() {
			              $(".citylist", this.domNode).is(":hidden") ? $(".citylist",
			                  this.domNode).show() : $(".citylist", this.domNode)
			                  .hide();
		              }.bind(this));
		          // 为辅助的字母绑定单击事件
		          $(".letters > a", this.domNode).each(function(index, elem) {
			          $(elem).click(this._onLettersClick);
		          }.bind(this));

		          // 为城市列表主体内容 和 头部中的城市 绑定单击事件
		          $(".assist > a, .citys >a", this.domNode).each(
		              function(index, elem) {
			              $(elem).click(lang.hitch(this, this._onCityClick));
		              }.bind(this));
	          },
	          /** 触发字母时的函数 */
	          _onLettersClick : function(evt) {
		          var letter = evt.target.innerHTML;
		          $("table.cityGroupDiv").each(function(index, elem) {
			          if ($(elem).attr("name") == letter) {
				          // 设置$("#content")元素滚动条的偏移,注意此时要设置$("#content")的position,
				          // 此时$(elem)[0].offsetTop的值才会是相对于父元素的偏移,否则就是相对于浏览器的偏移
				          $("#content")[0].scrollTop = $(elem)[0].offsetTop;
			          }
		          });
	          },
	          /** 触发城市时的函数 */
	          _onCityClick : function(evt) {
		          debugger
		          // 在使用传递的参数时还需要 使用JSON.parse将字符串转换为json对象,才可以使用
		          var city = JSON.parse(evt.target.getAttribute("data"));
		          $(".city-con .city").text(city.name);
		          $(".citylist").hide();
		          this.selCityCode = city.code;
	          }
	        });
    });